import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class Test_dio extends StatelessWidget {
  const Test_dio({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: const Text('Test_dio')),
        body:const FutureBuilderRouteState()
    );
  }
}



class FutureBuilderRouteState extends StatefulWidget {
  const FutureBuilderRouteState({super.key});

  @override
  State<FutureBuilderRouteState> createState() => _FutureBuilderRouteState();
}


class _FutureBuilderRouteState extends State<FutureBuilderRouteState> {
  final Dio _dio = Dio();

  @override
  Widget build(BuildContext context) {

    return Container(
      alignment: Alignment.center,
      child: FutureBuilder(
          future: _dio.get("https://api.github.com/orgs/flutterchina/repos"),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            //请求完成
            if (snapshot.connectionState == ConnectionState.done) {
              Response response = snapshot.data;
              //发生错误
              if (snapshot.hasError) {
                return Text(snapshot.error.toString());
              }
              //请求成功，通过项目信息构建用于显示项目名称的ListView
              return ListView(
                children: response.data.map<Widget>((e) =>
                    ListTile(title: Text(e["full_name"]))
                ).toList(),
              );
            }
            //请求未完成时弹出loading
            return const CircularProgressIndicator();
          }
      ),
    );
  }
}

class Http {
  // 单例模式
  static final Http _instance = Http._internal();
  factory Http() => _instance;

  late Dio dio;

  Http._internal() {
    BaseOptions options = BaseOptions(
      baseUrl: "https://api.example.com", // 统一 BaseUrl
      connectTimeout: const Duration(seconds: 10),
      receiveTimeout: const Duration(seconds: 15),
      headers: {
        "Content-Type": "application/json",
      },
    );

    dio = Dio(options);

    // 添加拦截器
    dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        print("请求地址: ${options.baseUrl}${options.path}");
        print("请求参数: ${options.data ?? options.queryParameters}");
        // 如果需要加 token，可以在这里统一处理
        // options.headers["Authorization"] = "Bearer xxx";
        return handler.next(options);
      },
      onResponse: (response, handler) {
        print("响应数据: ${response.data}");
        return handler.next(response);
      },
      onError: (DioException e, handler) {
        print("请求出错: ${e.message}");
        return handler.next(e);
      },
    ));
  }

  /// GET 请求
  Future<Response> get(
      String path, {
        Map<String, dynamic>? queryParameters,
        Options? options,
      }) async {
    return await dio.get(path, queryParameters: queryParameters, options: options);
  }

  /// POST 请求
  Future<Response> post(
      String path, {
        data,
        Map<String, dynamic>? queryParameters,
        Options? options,
      }) async {
    return await dio.post(path, data: data, queryParameters: queryParameters, options: options);
  }

  /// PUT 请求
  Future<Response> put(
      String path, {
        data,
        Map<String, dynamic>? queryParameters,
        Options? options,
      }) async {
    return await dio.put(path, data: data, queryParameters: queryParameters, options: options);
  }

  /// DELETE 请求
  Future<Response> delete(
      String path, {
        data,
        Map<String, dynamic>? queryParameters,
        Options? options,
      }) async {
    return await dio.delete(path, data: data, queryParameters: queryParameters, options: options);
  }

  /// 并发请求
  Future<List<Response>> all(List<Future<Response>> requests) async {
    return await Future.wait(requests);
  }

  /// 文件下载
  Future downloadFile(String url, String savePath) async {
    return await dio.download(url, savePath, onReceiveProgress: (count, total) {
      if (total != -1) {
        print("下载进度: ${(count / total * 100).toStringAsFixed(0)}%");
      }
    });
  }
}